// 生成随机ID
const generateId = () => Math.floor(Math.random() * 1000000).toString();

// 生成随机状态 (1: 启用, 0: 禁用)
const generateStatus = () => (Math.random() > 0.3 ? 1 : 0);

// 生成随机日期
const generateDate = () => {
  const date = new Date();
  date.setDate(date.getDate() - Math.floor(Math.random() * 365));
  return (
    date.toISOString().split("T")[0] + " " + date.toTimeString().split(" ")[0]
  );
};

// 生成随机用户名
const generateUsername = () => {
  const prefixes = ["user", "admin", "test", "lessee", "guest"];
  return (
    prefixes[Math.floor(Math.random() * prefixes.length)] +
    Math.floor(Math.random() * 1000)
  );
};

// 生成随机手机号
const generatePhone = () =>
  "13" +
  Math.floor(Math.random() * 100000000)
    .toString()
    .padStart(9, "0");

// 生成随机邮箱
const generateEmail = () => {
  const domains = ["example.com", "test.com", "lessee.com", "admin.com"];
  return (
    generateUsername() +
    "@" +
    domains[Math.floor(Math.random() * domains.length)]
  );
};

// 生成随机频道名称
const generateChannelName = () => {
  const prefixes = ["新闻", "娱乐", "体育", "科技", "财经", "教育", "健康"];
  return prefixes[Math.floor(Math.random() * prefixes.length)] + "频道";
};

// 生成随机频道编码
const generateChannelCode = () => "CH" + Math.floor(Math.random() * 10000);

// 生成随机分区名称
const generatePartitionName = () => {
  const prefixes = ["热门", "推荐", "最新", "精选", "专题"];
  return prefixes[Math.floor(Math.random() * prefixes.length)] + "分区";
};

// 生成用户测试数据
export const generateUserMockData = (count = 10) => {
  return Array.from({ length: count }, () => ({
    id: generateId(),
    username: generateUsername(),
    phone: generatePhone(),
    email: generateEmail(),
    status: generateStatus(),
    createTime: generateDate()
  }));
};

// 生成频道测试数据
export const generateChannelMockData = (count = 10) => {
  return Array.from({ length: count }, () => ({
    id: generateId(),
    name: generateChannelName(),
    code: generateChannelCode(),
    status: generateStatus(),
    createTime: generateDate()
  }));
};

// 生成分区测试数据
export const generatePartitionMockData = (count = 10, channels = []) => {
  // 如果没有提供频道数据，生成一些默认频道
  if (channels.length === 0) {
    channels = generateChannelMockData(5);
  }

  return Array.from({ length: count }, () => {
    const channel = channels[Math.floor(Math.random() * channels.length)];
    return {
      id: generateId(),
      name: generatePartitionName(),
      channelName: channel.name,
      channelId: channel.id,
      sort: Math.floor(Math.random() * 100),
      createTime: generateDate()
    };
  });
};

// 在开发环境下提供全局测试数据
if (process.env.NODE_ENV === "development") {
  // 生成测试数据
  const mockUsers = generateUserMockData();
  const mockChannels = generateChannelMockData();
  const mockPartitions = generatePartitionMockData(15, mockChannels);

  // 挂载到window对象，方便在控制台访问
  (window as any).mockData = {
    users: mockUsers,
    channels: mockChannels,
    partitions: mockPartitions,
    generateUserMockData,
    generateChannelMockData,
    generatePartitionMockData
  };

  console.log("测试数据已生成，可通过 window.mockData 访问");
}

/**
 * 生成设备模拟数据
 * @param count 生成数量
 * @param lesseeId 租户ID
 * @returns 设备数据数组
 */
export function generateDeviceMockData(count: number, lesseeId: string) {
  const devices = [];
  const types = ["摄像头", "广播机", "对讲设备"];
  const deviceGroups = ["默认设备组", "进口设备组", "广播设备组"];
  const lesseeNames = ["测试租户1", "测试租户2", "测试租户3"];
  const dealerNames = ["铭源通总经销", "其他经销商"];

  for (let i = 1; i <= count; i++) {
    const type = types[Math.floor(Math.random() * types.length)];
    const deviceGroup =
      deviceGroups[Math.floor(Math.random() * deviceGroups.length)];
    const lesseeName =
      lesseeNames[Math.floor(Math.random() * lesseeNames.length)];
    const dealerName =
      dealerNames[Math.floor(Math.random() * dealerNames.length)];
    const dealerId = dealerName === "铭源通总经销" ? "1" : "2";

    devices.push({
      id: `${10000 + i}`,
      name: `${type === "摄像头" ? "监控摄像头" : type === "广播机" ? "广播设备" : "对讲设备"}${i}`,
      code: `${type === "摄像头" ? "CAM" : type === "广播机" ? "BC" : "TALK"}-${(100 + i).toString().padStart(3, "0")}`,
      type,
      deviceGroup,
      lesseeId,
      lesseeName,
      dealerId,
      dealerName,
      remark: `${type} ${deviceGroup} ${i} 号设备${Math.random() > 0.5 ? " - 前门监控" : Math.random() > 0.5 ? " - 大厅广播" : ""}`,
      createTime: new Date(
        Date.now() - Math.random() * 30 * 24 * 60 * 60 * 1000
      )
        .toISOString()
        .replace("T", " ")
        .substr(0, 19)
    });
  }

  return devices;
}

// 生成设备关联模拟数据
export function generateDeviceRelationMockData(
  count: number,
  lesseeId: string | number,
  devices: any[]
): any[] {
  const statusOptions = ["激活", "未激活", "已禁用"];
  const deviceTypes = ["摄像头", "广播机", "对讲设备"];
  const dealerNames = ["铭源通总经销", "诚信设备经销", "科技设备供应商"];
  const lesseeName = "测试租户1";

  // 确保有设备数据可用
  if (devices.length === 0) {
    // 如果没有设备数据，生成一些临时设备
    devices = Array.from({ length: 10 }, (_, i) => ({
      id: `${i + 1}`,
      name: `测试设备${i + 1}`,
      type: deviceTypes[Math.floor(Math.random() * deviceTypes.length)]
    }));
  }

  return Array.from({ length: count }, (_, i) => {
    const mainDeviceIndex = Math.floor(Math.random() * devices.length);
    let relatedDeviceIndex;
    // 确保主设备和关联设备不是同一个
    do {
      relatedDeviceIndex = Math.floor(Math.random() * devices.length);
    } while (relatedDeviceIndex === mainDeviceIndex);

    const mainDevice = devices[mainDeviceIndex];
    const relatedDevice = devices[relatedDeviceIndex];

    return {
      id: `${i + 1}`,
      mainDeviceId: mainDevice.id,
      mainDeviceName: mainDevice.name,
      mainDeviceType: mainDevice.type,
      relatedDeviceId: relatedDevice.id,
      relatedDeviceName: relatedDevice.name,
      relatedDeviceType: relatedDevice.type,
      relationStatus:
        statusOptions[Math.floor(Math.random() * statusOptions.length)],
      lesseeId: lesseeId.toString(),
      lesseeName,
      dealerId: `${Math.floor(Math.random() * 3) + 1}`,
      dealerName: dealerNames[Math.floor(Math.random() * dealerNames.length)],
      createTime: new Date(
        Date.now() - Math.random() * 30 * 24 * 60 * 60 * 1000
      )
        .toISOString()
        .replace("T", " ")
        .split(".")[0]
    };
  });
}

// 在文件末尾添加以下函数

/**
 * 生成设备分组模拟数据
 * @param count 生成数量
 * @param lesseeId 租户ID
 * @returns 设备分组数据数组
 */
export function generateDeviceGroupMockData(count: number, lesseeId: string) {
  const groups = [];
  const statusOptions = ["激活", "停用"];
  const lesseeNames = ["测试租户1", "测试租户2", "测试租户3"];
  const dealerNames = ["铭源通总经销", "其他经销商"];

  for (let i = 1; i <= count; i++) {
    const status =
      statusOptions[Math.floor(Math.random() * statusOptions.length)];
    const lesseeName =
      lesseeNames[Math.floor(Math.random() * lesseeNames.length)];
    const dealerName =
      dealerNames[Math.floor(Math.random() * dealerNames.length)];
    const dealerId = dealerName === "铭源通总经销" ? "1" : "2";
    const deviceCount = Math.floor(Math.random() * 20) + 1;

    groups.push({
      id: `${i}`,
      name: `${["监控设备组", "广播设备组", "应急设备组", "备用设备组"][Math.floor(Math.random() * 4)]}${i}`,
      deviceCount,
      status,
      lesseeId,
      lesseeName,
      dealerId,
      dealerName,
      createTime: new Date(
        Date.now() - Math.random() * 30 * 24 * 60 * 60 * 1000
      )
        .toISOString()
        .replace("T", " ")
        .substr(0, 19)
    });
  }

  return groups;
}

// 添加频道成员模拟数据生成函数
export function generateChannelMembersMockData(
  count: number,
  lesseeId: string
) {
  const data = [];
  const channels = [
    { id: 1001, name: "城公共频道" },
    { id: 1002, name: "研发部私有频道" },
    { id: 1003, name: "测试频道" }
  ];
  const users = [
    { id: "168-A", userName: "张三" },
    { id: "168-B", userName: "李四" },
    { id: "251-A", userName: "王五" },
    { id: "251-B", userName: "赵六" }
  ];
  const priorities = [1, 2, 3, 4, 5];

  for (let i = 1; i <= count; i++) {
    const randomChannel = channels[Math.floor(Math.random() * channels.length)];
    const randomUser = users[Math.floor(Math.random() * users.length)];
    const randomPriority =
      priorities[Math.floor(Math.random() * priorities.length)];
    const date = new Date();
    date.setDate(date.getDate() - Math.floor(Math.random() * 30));

    data.push({
      id: i.toString(),
      channelId: randomChannel.id,
      channelName: randomChannel.name,
      userId: randomUser.id,
      userName: randomUser.userName,
      priority: randomPriority,
      lesseeId,
      lesseeName: "测试租户",
      dealerId: "1",
      dealerName: "经销商总经销",
      createTime: date.toISOString().replace("T", " ").substring(0, 19)
    });
  }

  return data;
}

/**
 * 生成事件模拟数据
 * @param count 生成数量
 * @param lesseeId 租户ID
 * @returns 事件数据数组
 */
export function generateEventMockData(count: number, lesseeId: string) {
  const events = [];
  const statusOptions = ["启用", "禁用"];
  const lesseeNames = ["测试租户1", "测试租户2", "测试租户3"];
  const dealerNames = ["铭源通总经销", "其他经销商"];
  const triggerConditions = [
    "设备离线超过5分钟",
    "温度超过阈值",
    "湿度低于阈值",
    "电压异常",
    "烟雾报警触发"
  ];
  const actions = [
    "发送邮件通知",
    "触发警报",
    "自动重启设备",
    "记录日志",
    "切换到备用设备"
  ];

  for (let i = 1; i <= count; i++) {
    const status =
      statusOptions[Math.floor(Math.random() * statusOptions.length)];
    const lesseeName =
      lesseeNames[Math.floor(Math.random() * lesseeNames.length)];
    const dealerName =
      dealerNames[Math.floor(Math.random() * dealerNames.length)];
    const dealerId = dealerName === "铭源通总经销" ? "1" : "2";
    const triggerCondition =
      triggerConditions[Math.floor(Math.random() * triggerConditions.length)];
    const action = actions[Math.floor(Math.random() * actions.length)];

    events.push({
      id: `${i}`,
      name: `${["设备监控", "环境监测", "安全警报", "系统状态", "网络监控"][Math.floor(Math.random() * 5)]}事件${i}`,
      status,
      lesseeId,
      lesseeName,
      dealerId,
      dealerName,
      triggerCondition,
      action,
      remark: `${status === "启用" ? "正常运行中" : "已禁用"} - ${Math.random() > 0.5 ? "重要事件" : "一般事件"}`,
      createTime: new Date(
        Date.now() - Math.random() * 30 * 24 * 60 * 60 * 1000
      )
        .toISOString()
        .replace("T", " ")
        .substr(0, 19)
    });
  }

  return events;
}

/**
 * 生成任务模拟数据
 * @param count 生成数量
 * @param lesseeId 租户ID
 * @returns 任务数据数组
 */
export function generateTaskMockData(count: number, lesseeId: string) {
  const tasks = [];
  const statusOptions = ["启用", "禁用", "执行中", "已完成"];
  const lesseeNames = ["测试租户1", "测试租户2", "测试租户3"];
  const dealerNames = ["铭源通总经销", "其他经销商"];
  const triggerConditions = [
    "定时执行",
    "设备状态变化",
    "数据达到阈值",
    "手动触发",
    "系统启动时"
  ];
  const actions = ["发送报告", "备份数据", "重启设备", "清理日志", "同步配置"];

  for (let i = 1; i <= count; i++) {
    const status =
      statusOptions[Math.floor(Math.random() * statusOptions.length)];
    const lesseeName =
      lesseeNames[Math.floor(Math.random() * lesseeNames.length)];
    const dealerName =
      dealerNames[Math.floor(Math.random() * dealerNames.length)];
    const dealerId = dealerName === "铭源通总经销" ? "1" : "2";
    const triggerCondition =
      triggerConditions[Math.floor(Math.random() * triggerConditions.length)];
    const action = actions[Math.floor(Math.random() * actions.length)];

    tasks.push({
      id: `${i}`,
      name: `${["数据备份", "系统检查", "设备维护", "日志清理", "配置同步"][Math.floor(Math.random() * 5)]}任务${i}`,
      status,
      lesseeId,
      lesseeName,
      dealerId,
      dealerName,
      triggerCondition,
      action,
      remark: `${status === "启用" ? "正常运行中" : status === "执行中" ? "正在执行" : status === "已完成" ? "已完成执行" : "已禁用"} - ${Math.random() > 0.5 ? "重要任务" : "一般任务"}`,
      createTime: new Date(
        Date.now() - Math.random() * 30 * 24 * 60 * 60 * 1000
      )
        .toISOString()
        .replace("T", " ")
        .substr(0, 19)
    });
  }

  return tasks;
}

/**
 * 生成触发器模拟数据
 * @param count 生成数量
 * @param lesseeId 租户ID
 * @returns 触发器数据数组
 */
export function generateTriggerMockData(count: number, lesseeId: string) {
  const triggers = [];
  const statusOptions = ["启用", "禁用"];
  const lesseeNames = ["测试租户1", "测试租户2", "测试租户3"];
  const dealerNames = ["铭源通总经销", "其他经销商"];
  const triggerConditions = [
    "设备离线超过5分钟",
    "温度超过阈值",
    "湿度低于阈值",
    "电压异常",
    "烟雾报警触发",
    "视频移动侦测",
    "声音超过阈值",
    "门禁未授权访问"
  ];
  const actions = [
    "发送邮件通知",
    "触发警报",
    "自动重启设备",
    "记录日志",
    "切换到备用设备",
    "推送消息到手机",
    "启动录像",
    "锁定门禁"
  ];

  for (let i = 1; i <= count; i++) {
    const status =
      statusOptions[Math.floor(Math.random() * statusOptions.length)];
    const lesseeName =
      lesseeNames[Math.floor(Math.random() * lesseeNames.length)];
    const dealerName =
      dealerNames[Math.floor(Math.random() * dealerNames.length)];
    const dealerId = dealerName === "铭源通总经销" ? "1" : "2";
    const triggerCondition =
      triggerConditions[Math.floor(Math.random() * triggerConditions.length)];
    const action = actions[Math.floor(Math.random() * actions.length)];

    triggers.push({
      id: `${i}`,
      name: `${["设备监控", "环境监测", "安全警报", "系统状态", "网络监控", "门禁控制", "视频分析"][Math.floor(Math.random() * 7)]}触发器${i}`,
      triggerCondition,
      action,
      status,
      lesseeId,
      lesseeName,
      dealerId,
      dealerName,
      createTime: new Date(
        Date.now() - Math.random() * 30 * 24 * 60 * 60 * 1000
      )
        .toISOString()
        .replace("T", " ")
        .substr(0, 19)
    });
  }

  return triggers;
}

/**
 * 生成资源模拟数据
 * @param count 生成数量
 * @param lesseeId 租户ID
 * @returns 资源数据数组
 */
export function generateResourceMockData(count: number, lesseeId: string) {
  const resources = [];
  const typeOptions = ["普通音频文件", "TTS"];
  const lesseeNames = ["测试租户1", "测试租户2", "测试租户3"];
  const dealerNames = ["铭源通总经销", "其他经销商"];
  const remarkOptions = [
    "每日晨间广播音频",
    "紧急情况警报音",
    "文本转语音包",
    "系统背景音乐",
    "提示音效",
    "公告语音"
  ];

  for (let i = 1; i <= count; i++) {
    const type = typeOptions[Math.floor(Math.random() * typeOptions.length)];
    const lesseeName =
      lesseeNames[Math.floor(Math.random() * lesseeNames.length)];
    const dealerName =
      dealerNames[Math.floor(Math.random() * dealerNames.length)];
    const dealerId = dealerName === "铭源通总经销" ? "1" : "2";
    const remark =
      remarkOptions[Math.floor(Math.random() * remarkOptions.length)];

    resources.push({
      id: `${i}`,
      name: `${["晨间广播", "紧急警报", "TTS语音包", "背景音乐", "提示音效", "系统公告"][Math.floor(Math.random() * 6)]}${i}`,
      code: `${i}`,
      type,
      uri:
        type === "普通音频文件"
          ? `/assets/${["morning_broadcast", "emergency_alarm", "background_music", "prompt_sound", "system_announcement"][Math.floor(Math.random() * 5)]}.${["mp3", "wav", "ogg"][Math.floor(Math.random() * 3)]}`
          : `/assets/tts_voice_pak${Math.floor(Math.random() * 3) + 1}`,
      lesseeId,
      lesseeName,
      dealerId,
      dealerName,
      remark,
      createTime: new Date(
        Date.now() - Math.random() * 30 * 24 * 60 * 60 * 1000
      )
        .toISOString()
        .replace("T", " ")
        .substr(0, 19)
    });
  }

  return resources;
}

/**
 * 生成时间切片模拟数据
 * @param count 生成数量
 * @param lesseeId 租户ID
 * @returns 时间切片数据数组
 */
export function generateTimeSliceMockData(count: number, lesseeId: string) {
  const timeSlices = [];
  const statusOptions = ["激活", "停用"];
  const lesseeNames = ["测试租户1", "测试租户2", "测试租户3"];
  const dealerNames = ["铭源通总经销", "其他经销商"];

  for (let i = 1; i <= count; i++) {
    const status =
      statusOptions[Math.floor(Math.random() * statusOptions.length)];
    const lesseeName =
      lesseeNames[Math.floor(Math.random() * lesseeNames.length)];
    const dealerName =
      dealerNames[Math.floor(Math.random() * dealerNames.length)];
    const dealerId = dealerName === "铭源通总经销" ? "1" : "2";

    // 生成随机开始时间（过去30天内）
    const startDate = new Date(
      Date.now() - Math.random() * 30 * 24 * 60 * 60 * 1000
    );
    // 生成随机结束时间（开始时间后1-24小时）
    const endDate = new Date(
      startDate.getTime() + (Math.random() * 23 + 1) * 60 * 60 * 1000
    );

    timeSlices.push({
      id: `${i}`,
      name: `时间切片${i}`,
      startTime: startDate.toISOString().replace("T", " ").substr(0, 19),
      endTime: endDate.toISOString().replace("T", " ").substr(0, 19),
      status,
      lesseeId,
      lesseeName,
      dealerId,
      dealerName,
      createTime: new Date(
        Date.now() - Math.random() * 30 * 24 * 60 * 60 * 1000
      )
        .toISOString()
        .replace("T", " ")
        .substr(0, 19)
    });
  }

  return timeSlices;
}
